const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const session = require('express-session')
const bcrypt = require('bcryptjs')
const csrf = require('csurf')

const app = express()
const port = 3000

// ================== 中间件配置 ==================
app.use(bodyParser.json())

// CORS 配置
app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:8080'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token']
}))

// 会话配置
app.use(session({
  secret: 'your-secure-secret-key-here', // 生产环境应使用环境变量
  resave: false,
  saveUninitialized: false,
  cookie: { 
    secure: process.env.NODE_ENV === 'production', // 生产环境启用 HTTPS
    sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax',
    maxAge: 24 * 60 * 60 * 1000 // 24小时
  }
}))

// CSRF 保护配置
const csrfProtection = csrf({
  cookie: {
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax'
  }
})

// ================== 路由配置 ==================

// 获取 CSRF 令牌
app.get('/api/csrf-token', csrfProtection, (req, res) => {
  res.json({ csrfToken: req.csrfToken() })
})

// 处理 OPTIONS 预检请求
app.options('*', (req, res) => res.sendStatus(204))

// ================== 模拟数据库 ==================
const pets = [
  { id: 1, name: '小黑', image: 'path/to/image1.jpg', description: '活泼的小狗' },
  { id: 2, name: '小白', image: 'path/to/image2.jpg', description: '温顺的小猫' }
]

const users = [
  { 
    id: 1, 
    username: 'user1', 
    password: bcrypt.hashSync('password1', 12),
    email: 'user1@example.com',
    createdAt: new Date()
  }
]

// ================== 宠物路由 ==================
app.get('/pets', (req, res) => {
  res.json(pets)
})

app.post('/adopt/:id', csrfProtection, (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ success: false, message: '请先登录' })
  }
  
  const petId = parseInt(req.params.id)
  const petIndex = pets.findIndex(p => p.id === petId)
  
  if (petIndex === -1) {
    return res.status(404).json({ success: false, message: '未找到该宠物' })
  }
  
  pets.splice(petIndex, 1)
  res.json({ success: true, message: '领养成功' })
})

// ================== 用户认证路由 ==================
app.post('/api/register', csrfProtection, async (req, res) => {
  try {
    const { username, password, email } = req.body
    
    // 验证输入
    if (!username || !password || !email) {
      return res.status(400).json({ 
        success: false,
        message: '需要提供用户名、密码和邮箱' 
      })
    }
    
    // 检查用户是否存在
    if (users.some(u => u.username === username)) {
      return res.status(409).json({ 
        success: false,
        message: '用户名已存在' 
      })
    }
    
    // 创建用户
    const newUser = {
      id: users.length + 1,
      username,
      password: bcrypt.hashSync(password, 12),
      email,
      createdAt: new Date()
    }
    
    users.push(newUser)
    
    // 自动登录
    req.session.userId = newUser.id
    
    res.status(201).json({ 
      success: true,
      data: {
        id: newUser.id,
        username: newUser.username,
        email: newUser.email
      }
    })
    
  } catch (error) {
    console.error('注册错误:', error)
    res.status(500).json({ 
      success: false,
      message: '服务器内部错误' 
    })
  }
})

app.post('/api/login', csrfProtection, (req, res) => {
  const { username, password } = req.body
  
  const user = users.find(u => u.username === username)
  
  if (!user || !bcrypt.compareSync(password, user.password)) {
    return res.status(401).json({ 
      success: false,
      message: '用户名或密码错误' 
    })
  }
  
  req.session.userId = user.id
  res.json({ 
    success: true,
    data: {
      id: user.id,
      username: user.username,
      email: user.email
    }
  })
})

app.get('/api/profile', (req, res) => {
  if (!req.session.userId) {
    return res.status(401).json({ 
      success: false,
      message: '未登录' 
    })
  }
  
  const user = users.find(u => u.id === req.session.userId)
  
  if (!user) {
    return res.status(404).json({ 
      success: false,
      message: '用户不存在' 
    })
  }
  
  res.json({ 
    success: true,
    data: {
      id: user.id,
      username: user.username,
      email: user.email
    }
  })
})

app.post('/api/logout', csrfProtection, (req, res) => {
  req.session.destroy(err => {
    if (err) {
      console.error('退出错误:', err)
      return res.status(500).json({ 
        success: false,
        message: '退出失败' 
      })
    }
    res.clearCookie('connect.sid')
    res.json({ 
      success: true,
      message: '退出成功' 
    })
  })
})

// ================== 错误处理中间件 ==================
app.use((err, req, res, next) => {
  if (err.code === 'EBADCSRFTOKEN') {
    return res.status(403).json({
      success: false,
      message: '无效的 CSRF 令牌'
    })
  }
  
  console.error('全局错误:', err)
  res.status(500).json({ 
    success: false,
    message: '服务器内部错误' 
  })
})

// ================== 启动服务器 ==================
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`)
  console.log(`当前环境: ${process.env.NODE_ENV || 'development'}`)
  console.log(`CSRF 保护已${process.env.NODE_ENV === 'production' ? '启用' : '测试模式'}`)
})